package com.briup.store.service.impl;

import com.briup.common.exception.SystemException;
import com.briup.common.response.CodeAndMessageEnum;
import com.briup.common.response.PageTemplate;
import com.briup.common.utils.BeanCopyUtils;
import com.briup.store.domain.dto.OrderItemInsertDTO;
import com.briup.store.mapper.GoodsMapper;
import com.briup.store.domain.pojo.Goods;
import com.briup.store.service.GoodsService;
import com.briup.store.domain.vo.GoodsGetDetailVO;
import com.briup.store.domain.vo.GoodsGetHotVO;
import com.briup.store.domain.vo.GoodsGetListVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author qinyc
* @description 针对表【es_goods(商品表)】的数据库操作Service实现
* @createDate 2024-12-24 09:16:52
*/
@Service
public class GoodsServiceImpl implements GoodsService{

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public PageTemplate<GoodsGetHotVO> getHot(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        //查询所有商品信息并按照销量排序（倒序）
        List<Goods> goodsList = goodsMapper.getAllGoodsDesc();
        PageInfo<Goods> goods = new PageInfo<>(goodsList);
        //Bean集合拷贝
        return new PageTemplate<GoodsGetHotVO>(goods.getTotal(), BeanCopyUtils.copyBeanList(goods.getList(),GoodsGetHotVO.class));
    }

    @Override
    public GoodsGetDetailVO getGoodsDetail(Integer id) {
        /**
         * 参数校验
         */
        Goods goods = goodsMapper.getGoodsById(id);

        return BeanCopyUtils.copyBean(goods,GoodsGetDetailVO.class);
    }

    @Override
    public List<Goods> queryGoodByIds(List<Integer> ids) {
        return goodsMapper.queryGoodByIds(ids);
    }

    @Override
    public PageTemplate<GoodsGetListVO> getList(Integer categoryId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Goods> goodsList = goodsMapper.getListByCategory(categoryId);
        PageInfo<Goods> goods = new PageInfo<>(goodsList);
        return new PageTemplate<GoodsGetListVO>(goods.getTotal(),BeanCopyUtils.copyBeanList(goods.getList(),GoodsGetListVO.class));
    }

    @Override
    public void updateStock(List<OrderItemInsertDTO> items) {
        for (OrderItemInsertDTO item : items) {
            Goods goods = goodsMapper.getGoodsById(item.getGoods());
            //计算最新库存
            int storeNum = goods.getStoreNum() - item.getNum();
            if(storeNum < 0) {
                throw new SystemException(CodeAndMessageEnum.GOODSTOCK_IS_NOT_ENOUGH);
            }
            //修改库存
            goods.setStoreNum(storeNum);

            //更新商品库存信息
            goodsMapper.updateGood(goods);
        }
    }
}




